package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.redis.service.ITravelStratisVoRedisService;
import cn.wolfcode.wolf2w.redis.vo.TravelStatisVo;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private TravelRepository travelRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private ITravelStratisVoRedisService travelStratisVoRedisService;

    @Override
    public void save(Travel travel) {
         System.out.println(travel.getId());  // 打印的为空
         travel.setId(null);  // （要set null）如果id=“”,Spring-data-MongoDB 不会自动生成id注入 （数据库存在，但是不会将注入参数对象中travel）  isPresent
        travelRepository.save(travel);
         System.out.println(travel.getId());  //打印出保存后的id值
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        // 逻辑严谨
        Optional<Travel> optional = travelRepository.findById(id);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Travel> listAll() {
        return travelRepository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();

        // 状态：1（待审核）、-1（已拒绝）
        if(qo.getState() == TravelQuery.STATE_WAITING){
            query.addCriteria(Criteria.where("state").is(Travel.STATE_WAITING));
        }
        if(qo.getState() == TravelQuery.STATE_RELEASE){
            query.addCriteria(Criteria.where("state").is(Travel.STATE_RELEASE));
        }
        if(qo.getState() == TravelQuery.STATE_REJECT){
            query.addCriteria(Criteria.where("state").is(Travel.STATE_REJECT));
        }

        // 目的地
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        // 出行天数
        if (qo.getDay() != null){
            query.addCriteria(Criteria.where("day").lte(qo.getDay().getMax()).gte(qo.getDay().getMin()));
        }
        // 人均花费
        if (qo.getPerExpend() != null){
            query.addCriteria(Criteria.where("perExpend").lte(qo.getPerExpend().getMax()).gte(qo.getPerExpend().getMin()));
        }
        // 最新排序
        Pageable pageable = null;
        if (qo.getOrderType() == TravelQuery.ORDER_NEW){
            pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");
        }else if(qo.getOrderType() == TravelQuery.ORDER_HOT){  //最热排序
            pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"viewnum");
        }else {  // 默认id排序
            pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        }

        // 发布了, 并且是公开的才显示
     if ("YES".equals(qo.getStateReleaseAndPublic())){
         Criteria criteria = new Criteria();
         criteria.andOperator(Criteria.where("state").is(Travel.STATE_RELEASE),Criteria.where("isPublic").is(Travel.ISPUBLIC_YES));
         query.addCriteria(criteria);
     }

        Page<Travel> page = DBHelper.query(mongoTemplate, query, Travel.class, pageable);
        for (Travel travel : page) {
            // 设置作者
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userInfo);
        }
        return page;
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        // 目的地name
        String name = destinationService.get(travel.getDestId()).getName();
        travel.setDestName(name);
        //发布时间
        travel.setReleaseTime(null);
        //最新更新时间内
        travel.setLastUpdateTime(null);
        if (StringUtils.hasLength(travel.getId())){
            // 5个数
            Travel tra = this.get(travel.getId());
            travel.setReplynum(tra.getReplynum());
            travel.setViewnum(tra.getViewnum());
            travel.setFavornum(tra.getFavornum());
            travel.setSharenum(tra.getSharenum());
            travel.setThumbsupnum(tra.getThumbsupnum());
            this.update(travel);
        }else {
            //创建时间
            travel.setCreateTime(new Date());
            this.save(travel);
        }
    }

    @Override
    public void changeState(String id, int state) {
        // 获取当前的游记
        Travel travel = this.get(id);
        // 满足当前游记 不为空且 状态为待审核才进行审核；不满足，抛异常
        if (travel == null || travel.getState() != Travel.STATE_WAITING) {
            throw new LogicException("不满足审核条件！");
        }

        travel.setReleaseTime(new Date());  // 最后更新时间
        // 审核通过
        if (state == Travel.STATE_RELEASE){
            // 改变状态、发布时间和最后更新时间都为 当前时间
            travel.setState(Travel.STATE_RELEASE);
            travel.setCreateTime(new Date());
            // 记录审核信息（审核人、时间、审核意见。。）暂时不用
        }else if(state == Travel.STATE_REJECT){
            // 审核不通过
            // 改变状态、发布时间和最后更新时间都为 null
            travel.setState(Travel.STATE_REJECT);
            travel.setCreateTime(null);
            // 记录审核信息（审核人、时间、审核意见。。）暂时不用
        }
        // 更新
        this.update(travel);
    }

    @Override
    public void soldOut(String id, int state) {
        // 获取当前的游记
        Travel travel = this.get(id);
        travel.setReleaseTime(new Date());  // 最后更新时间
        // 下架状态，待审核状态
        travel.setState(Travel.STATE_WAITING);
        travel.setCreateTime(null);
        this.update(travel);
    }

    @Override
    public List<Travel> findByDestId(String id) {
        Pageable pageble = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        return travelRepository.findByDestId(id,pageble);
    }

    @Override
    public TravelStatisVo getStatisVo(String tid) {
        // 阅读数+1
        travelStratisVoRedisService.viewnumIncrease(tid,1);
        return travelStratisVoRedisService.getTravelStatisVo(tid);
    }

    @Override
    public List<String> getUserTravelFavor(String userId) {
        return travelStratisVoRedisService.getFavorList(userId);
    }

    @Override
    public List<Travel> findByDestName(String destName) {
        return travelRepository.findByDestName(destName);
    }
}
